const { log } = require('console')
const { resolve } = require('path')
const request = require('request')
const fs = require('fs')
const config = require("../config")
const AK = config.AIPainting.client_id
const SK = config.AIPainting.client_secret

/* 
图片通过百度ai绘图转换
*/
const AIPainting = async (req, res, next) => {
    try {
        const result = await main(req.body.image)
        var base64Data = JSON.parse(result).image.replace(/^data:image\/\w+;base64,/, "");
        var dataBuffer = Buffer.from(base64Data, 'base64'); // 这是另一种写法
        fs.writeFile("image.png", dataBuffer, "binary", function (err) {
            if (err) {
                next(err)
            } else {
                res.send("保存成功！");
            }
        });

    } catch (err) {
        next(err)
    }
}
/* 
图片上传
*/
const upload = (req, res, next) => {
    try {
        res.send("http://localhost:3000/" + "upload/" + req.file.filename)
    } catch (err) {
        next(err)
    }
}
//调用百度ai绘画
async function main(url) {
    var options = {
        'method': 'POST',
        'url': 'https://aip.baidubce.com/rest/2.0/image-process/v1/style_trans?access_token=' + await getBaiDuAccessToken(),
        'headers': {
            'Content-Type': 'application/x-www-form-urlencoded',
            'Accept': 'application/json'
        },
        form: {
            /* 
            cartoon：卡通画风格
            pencil：铅笔风格
            color_pencil：彩色铅笔画风格
            warm：彩色糖块油画风格
            wave：神奈川冲浪里油画风格
            lavender：薰衣草油画风格
            mononoke：奇异油画风格
            scream：呐喊油画风格
            gothic：哥特油画风格
            */
            'option': 'cartoon',
            url
        }
    };
    return new Promise((resolve, reject) => {
        request(options, function (error, response) {
            if (error) { reject(error) }
            resolve(response.body)
        });
    });
}

/**
 * 使用 AK，SK 生成鉴权签名（Access Token）
 * @return string 鉴权签名信息（Access Token）
 */
function getBaiDuAccessToken() {

    let options = {
        'method': 'POST',
        'url': 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=' + AK + '&client_secret=' + SK,
    }
    return new Promise((resolve, reject) => {
        request(options, (error, response) => {
            if (error) { reject(error) }
            else { resolve(JSON.parse(response.body).access_token) }
        })
    })
}

module.exports = {
    AIPainting,
    upload
}